<?php
/**
 * Created by PhpStorm.
 * User: Woo
 * Date: 2018/3/21
 * Time: 16:19
 */

namespace App\Http\Controllers\Api;



use App\Helper\ErrorCode;
use App\Helper\Helper;
use App\Http\Controllers\Controller;
use App\Jobs\SendMail;
use App\Mail\Register;
use App\Models\User;
use App\Task\SendMailTask;
use Carbon\Carbon;
use Hhxsv5\LaravelS\Swoole\Task\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class UserController extends Controller
{
    /**
     * @SWG\Post(
     *      path="/api/user/register",
     *      tags={"User"},
     *      summary="register",
     *      description="
     *      4444;//系统错误
     *     返回token30天过期",
     *      @SWG\Parameter(
     *          name="nick_name",
     *          description="昵称 |min:1|max:20",
     *          required=true,
     *          type="string",
     *          in="formData"
     *      ),
     *      @SWG\Parameter(
     *          name="email",
     *          description="|max:32",
     *          required=true,
     *          type="string",
     *          in="formData"
     *      ),
     *      @SWG\Parameter(
     *          name="password",
     *          description="|min:8|max:32",
     *          required=true,
     *          type="string",
     *          in="formData"
     *      ),
     *      @SWG\Parameter(
     *          name="face_url",
     *          description="url",
     *          required=false,
     *          type="string",
     *          in="formData"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation"
     *       ),
     *       @SWG\Response(response=400, description="Bad request"),
     *       security={
     *           {"api_key_security_example": {}}
     *       }
     *     )
     * @param Request $request
     * @return string
     */
    public function register(Request $request){
        $this->validate($request,[
            'email'=>'e-mail|unique:t_user,email|max:32',
            'nick_name'=>'string|min:1|max:20',
            'password'=>'string|min:8|max:32',
            'face_url'=>'string|url',
            'code'=>'required|integer'
        ]);
        $data = $request->only(['email', 'nick_name','password','face_url','code']);
//        if(Redis::get('register'.md5($data['email'])) <> $data['code']){
//            return Helper::returnError(ErrorCode::TOKEN_ERROR,'验证码错误');
//        };
        $salt = Helper::saltGen(6);
        $data_insert = [
            'nick_name'=>$data['nick_name'],
            'passwd'=>md5($salt.$data['password'].$salt),
            'email'=>$data['email'],
            'face_url'=>$data['face_url']??'',
            'salt'=>$salt,
        ];
        $user = User::create($data_insert);
        if($user){
            $token = Helper::tokenGen($data['nick_name']);
//            Redis::set('user_token'.$user['id'],$token,'EX',86400*30);
            return Helper::returnSuccess(['user_id'=>$user['id'],'token'=>$token]);
        }else{
            return HelPer::returnError(ErrorCode::SYS_ERROR,'注册失败');
        }
    }

    /**
     * @SWG\Get(
     *      path="/api/user/send/mail/code",
     *      tags={"User"},
     *      summary="发送验证码邮件",
     *      description="验证码15分钟有效",
     *      @SWG\Parameter(
     *          name="email",
     *          description="|max:32",
     *          required=true,
     *          type="string",
     *          in="query"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation"
     *       ),
     *       @SWG\Response(response=400, description="Bad request"),
     *       security={
     *           {"api_key_security_example": {}}
     *       }
     *     )
     * @param Request $request
     * @return string
     */
    public function getCode(Request $request){
        $this->validate($request, [
            'email'=>'required|e-mail'
        ]);
        $email = $request->input('email');
        $code = random_int(1000, 9999);
        Redis::set('register'.md5($email),$code,'EX',15*60);
        $data = ['view'=>Register::class,'param'=>['code'=>$code]];
//        $res = Task::deliver(new SendMailTask($email, $data));
        $res = SendMail::dispatch($email, $data);
        $res = dispatch(new SendMail($email, $data));
        if($res){
            return Helper::returnSuccess('register'.md5($email));
        }
        return Helper::returnError(ErrorCode::SYS_ERROR, '发送失败');

    }
    /**
     * @SWG\Post(
     *      path="/api/user/login",
     *      tags={"User"},
     *      summary="login",
     *      description="
     *     返回token30天过期",
     *      @SWG\Parameter(
     *          name="email",
     *          description="|max:32",
     *          required=true,
     *          type="string",
     *          in="formData"
     *      ),
     *      @SWG\Parameter(
     *          name="password",
     *          description="|min:8|max:32",
     *          required=true,
     *          type="string",
     *          in="formData"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation"
     *       ),
     *       @SWG\Response(response=400, description="Bad request"),
     *       security={
     *           {"api_key_security_example": {}}
     *       }
     *     )
     * @param Request $request
     * @return string
     */
    public function login(Request $request){
        $this->validate($request,[
            'email'=>'required|e-mail|max:32',
            'password'=>'required|string|min:8|max:32'
        ]);
        $data = $request->only(['email', 'password']);
        $user = User::where('email', $data['email'])->first();
        if($user && $user['passwd'] == md5($user['salt'].$data['password'].$user['salt'])){
            $token = Helper::tokenGen($user['nick_name']);
            if(env('APP_ENV')=='production'){
                Redis::set('user_token'.$user['id'],$token,'EX',86400*30);
            }
            return Helper::returnSuccess(['user_id'=>$user['id'],'token'=>$token]);
        }
        return Helper::returnError(ErrorCode::ACCOUNT_ERROR,'邮箱未注册或密码错误');
    }
    /**
     * @SWG\Post(
     *      path="/api/user/modify",
     *      tags={"User"},
     *      summary="modify",
     *      description="",
     *      @SWG\Parameter(
     *          name="u",
     *          description="user_id",
     *          required=true,
     *          type="integer",
     *          in="query"
     *      ),
     *      @SWG\Parameter(
     *          name="nick_name",
     *          description="",
     *          required=false,
     *          type="string",
     *          in="formData"
     *      ),
     *      @SWG\Parameter(
     *          name="password",
     *          description="",
     *          required=false,
     *          type="string",
     *          in="formData"
     *      ),
     *      @SWG\Parameter(
     *          name="face_url",
     *          description="头像链接",
     *          required=false,
     *          type="string",
     *          in="formData"
     *      ),
     *      @SWG\Parameter(
     *          name="token",
     *          description="与用户有关需要token",
     *          required=true,
     *          type="string",
     *          in="query"
     *      ),
     *      @SWG\Parameter(
     *          name="timestamp",
     *          description="",
     *          required=true,
     *          type="string",
     *          in="query"
     *      ),
     *      @SWG\Parameter(
     *          name="sign",
     *          description="",
     *          required=true,
     *          type="string",
     *          in="query"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation"
     *       ),
     *       @SWG\Response(response=400, description="Bad request"),
     *       security={
     *           {"api_key_security_example": {}}
     *       }
     *     )
     * @param Request $request
     * @return string
     */
    public function modify(Request $request){
        $this->validate($request,[
            'nick_name'=>'string|min:1|max:20',
            'password'=>'string|min:8|max:32',
            'face_url'=>'string|url',
            'u'=>'int|required'
        ]);
        $data = $request->only(['nick_name', 'password', 'face_url']);

        if(count($data) == 0){
            return Helper::returnError(ErrorCode::PARAM_EMPTY,'未提交数据');
        }
        $user = User::findOrFail($request->input('u'));
        if(isset($data['password'])){
            $data['passwd'] = md5($user['salt'].$data['password'].$user['salt']);
            unset($data['password']);
        }
        $res = $user->update($data);
        if($res){
            return Helper::returnSuccess(true);
        }
        return Helper::returnError(ErrorCode::SYS_ERROR,'修改失败');
    }
    /**
     * @SWG\Get(
     *      path="/api/user/info",
     *      tags={"User"},
     *      summary="user info",
     *      description="",
     *      @SWG\Parameter(
     *          name="u",
     *          description="user_id",
     *          required=true,
     *          type="integer",
     *          in="query"
     *      ),
     *      @SWG\Parameter(
     *          name="token",
     *          description="与用户有关需要token",
     *          required=true,
     *          type="string",
     *          in="query"
     *      ),
     *      @SWG\Parameter(
     *          name="timestamp",
     *          description="",
     *          required=true,
     *          type="string",
     *          in="query"
     *      ),
     *      @SWG\Parameter(
     *          name="sign",
     *          description="",
     *          required=true,
     *          type="string",
     *          in="query"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation"
     *       ),
     *       @SWG\Response(response=400, description="Bad request"),
     *       security={
     *           {"api_key_security_example": {}}
     *       }
     *     )
     * @param Request $request
     * @return string
     */

    public function userInfo(Request $request){
        $user = User::findOrFail($request->input('u'),['id as user_id','nick_name','face_url','email']);
        return Helper::returnSuccess($user);
    }
}